package com.fxw.mylibrary.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;

import com.fxw.mylibrary.PermissionActivity;
import com.fxw.mylibrary.R;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xianwen.fu
 * @version v1.0
 * @Title 请求权限util
 * @Description:
 * @Date 2016/03/22下午 1:59
 */
public class PermissionsUtil {

    private static volatile PermissionsUtil instance;
    private RequestPerissionsListeners mListeners;
    private Activity mActivity;
    //未授权集合 没有勾选不在提醒
    List<String> needRationalPermissionList;
    //勾选不在提醒
    List<String> deniedPermissionList;

    private PermissionsUtil() {
    }

    public static PermissionsUtil getInstance() {
        if (instance == null) {
            synchronized (PermissionsUtil.class) {
                if (instance == null) {
                    instance = new PermissionsUtil();
                }
            }
        }

        return instance;
    }

    /**
     * 权限被禁止 跳转到设置权限 弹框
     * @param context
     * @param message 提示内容
     * @param code
     */
    public void showSettingPermissions(final Activity context, String message, final int code) {
        new AlertDialog.Builder(context)
                .setTitle("警告")
                .setMessage(message)
                .setPositiveButton(context.getString(R.string.strs_sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                        intent.setData(uri);
                        context.startActivityForResult(intent, code);
                    }
                })
                .setNegativeButton(context.getString(R.string.strs_cancle), null)
                .create()
                .show();
    }

    /**
     * 多个权限检查是否APP已经拥有权限
     *
     * @param context
     * @param permissions 权限集合
     * @param requestCode 请求id判断
     */
    public PermissionsUtil requestArrayPermissions(Activity context, final int requestCode, final String... permissions) {
        mActivity = context;
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            if (mListeners != null)
                mListeners.requestPerissionsSuccess(requestCode);
            return this;
        }
        final List<String> deniedPermissions = findDeniedPermissions(context, permissions);
        if (needRationalPermissionList.size() == 0 && deniedPermissionList.size() == 0) {
            if (mListeners != null)
                mListeners.requestPerissionsSuccess(requestCode);
        }else if (deniedPermissions.size() > 0) {
            requestPermissions(context, deniedPermissions.toArray(new String[deniedPermissions.size()]), requestCode);
        } else {
            if (mListeners != null)
                mListeners.requestPerissionsSuccess(requestCode);
        }
        return this;
    }

    private void requestPermissions(Activity context, String[] permissions, int requestCode) {
        Intent intent = new Intent(context, PermissionActivity.class);
        intent.putExtra("permissions", permissions);
        intent.putExtra("requestCode", requestCode);
        intent.addFlags(268435456);
        context.startActivity(intent);
    }

    /**
     * 判断是否已经同意授权
     *
     * @param activity
     * @param permission 请求授权权限
     * @return 返回未授权 权限数据
     */
    @TargetApi(Build.VERSION_CODES.M)
    private List<String> findDeniedPermissions(Activity activity, String[] permission) {
        List<String> deniedPermissions = new ArrayList<>();
        needRationalPermissionList = new ArrayList<>();
        deniedPermissionList = new ArrayList<>();
        for (String value : permission) {
            if (activity.checkSelfPermission(value) != PackageManager.PERMISSION_GRANTED) {
                deniedPermissions.add(value);
                //判断是否勾选不在提醒
                if (mActivity.shouldShowRequestPermissionRationale(value)) {
                    needRationalPermissionList.add(value);
                } else {
                    deniedPermissionList.add(value);
                }
            }
        }
        return deniedPermissions;
    }

    /**
     * 判断是否获取权限成功
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //未授权集合 没有勾选不在提醒
        needRationalPermissionList = new ArrayList<>();
        //勾选不在提醒
        deniedPermissionList = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            //如果没有同意添加到集合
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                //判断是否勾选不在提醒
                if (mActivity.shouldShowRequestPermissionRationale(permissions[i])) {
                    needRationalPermissionList.add(permissions[i]);
                } else {
                    deniedPermissionList.add(permissions[i]);
                }
            }
        }
        if (needRationalPermissionList.size() > 0) {
            requestArrayPermissions(mActivity,requestCode,needRationalPermissionList.toArray(new String[needRationalPermissionList.size()]));
        } else if (deniedPermissionList.size() > 0) {
            if (mListeners != null)
                mListeners.requestPerissionsFailed(requestCode, deniedPermissionList, needRationalPermissionList);
        } else {
            if (mListeners != null)
                mListeners.requestPerissionsSuccess(requestCode);
        }

    }

    public interface RequestPerissionsListeners {
        /**
         * 获取权限成功
         *
         * @param requestCode
         */
        void requestPerissionsSuccess(int requestCode);

        /**
         * 获取权限失败
         *
         * @param requestCode
         * @param deniedPermissions   用户拒绝权限  勾选不再提醒 的权限集合
         * @param rationalPermissions 用户拒绝权限  但没有勾选不再提醒 集合
         */
        void requestPerissionsFailed(int requestCode, List<String> deniedPermissions, List<String> rationalPermissions);

    }

    /**
     * 设置获取权限监听
     *
     * @param listeners
     */
    public PermissionsUtil setRequestPerissionsListeners(RequestPerissionsListeners listeners) {
        mListeners = listeners;
        return this;
    }
}